package org.makcro.sms.services.chat.web.server.services;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.makcro.sms.services.chat.model.Agent;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.services.login.LoginService;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class LoginServiceImpl implements LoginService {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(LoginServiceImpl.class);
	
	/**
	 * Instance of login service
	 */
	private org.makcro.sms.services.chat.base.business.LoginService loginService;

	
	@Override
	public Boolean login(String username, String password) {

		Agent agent = loginService.authenticateAgent(username, password);

		if (agent != null) {
			
			// register agent with the current session
			registerUserWithTheCurrentSession( agent );
			
			logger.info(MessageFormat.format("Successful auth for user [{0}]", username));
			
			return true;
		
		} else {
			logger.info(MessageFormat.format("Failed auth for user [{0}] and password [{1}]", username, password));
			return false;
		}

	}
	
	private void registerUserWithTheCurrentSession(Agent agent){
		ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession session = currentRequestAttributes.getRequest().getSession( true );
		session.setAttribute( Constants.Session.CURRENT_USER, agent );
		logger.debug( MessageFormat.format( "User [{0}] registered with current session [{1}]", agent.getAgentUserName(), session.getId() ));
	}
	
	
	public void setLoginService(org.makcro.sms.services.chat.base.business.LoginService loginService) {
		this.loginService = loginService;
	}

}
